package com.yunpuvip.sachet.rest.common.aop;

import cn.stylefeng.roses.core.reqres.response.ResponseData;
import com.yunpuvip.sachet.modular.core.exception.RestServiceExceptionEnum;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * 异常信息拦截
 *
 * @author hyf
 * @date 2019-03-19
 **/
@ControllerAdvice
public class BaseControllerExceptionHandler {


    // 自拦截BindException
    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public ResponseData bindExceptionFount(Exception e) {
        System.out.println("fasheng cuowule ");
        StringBuilder stringBuilder = new StringBuilder();
        BindException bindException = (BindException) e;
        // 获取异常信息
        for (ObjectError objectError : bindException.getAllErrors()) {
            // 提取定义的错误信息,并组装返回给前端
            stringBuilder.append(objectError.getDefaultMessage()).append(" ");
        }
        return ResponseData.error(RestServiceExceptionEnum.PARAMETER_VALUE_EMPTY.getCode(), stringBuilder.toString());
    }
}